package com.bitcat.netdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    String urlString = "https://api.mhimg.cn/api/lishi/?format=json";
    TextView contentTv;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String message = (String) msg.obj;
            contentTv.setText(message);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        contentTv = findViewById(R.id.contentTv);
    }


    public void showData(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                Toast.makeText(MainActivity.this, "更新UI", Toast.LENGTH_SHORT).show();
//               runOnUiThread(new Runnable() {
//                   @Override
//                   public void run() {
//                       contentTv.setText("更新UI");
//                   }
//               });
                Message message = Message.obtain();
                message.obj = "比特猫编程";
                handler.sendMessage(message);
            }
        }).start();
    }

    public void httpUrlConnection(View view) {
        new Thread(() -> {
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");
                StringBuilder result = new StringBuilder();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    reader.close();
                    runOnUiThread(() -> contentTv.setText(result));
                }else{
                    runOnUiThread(() -> {
                        try {
                            contentTv.setText("请求失败："+conn.getResponseCode());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
               runOnUiThread(() -> contentTv.setText("请求失败："+e.getMessage()));
            }
        }).start();
    }

    public void requestByOkhttp(View view) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(urlString)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        e.printStackTrace();
                        contentTv.setText("请求失败："+e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (response.isSuccessful()){
                            String res = null;
                            try {
                                res = response.body().string();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
//                            contentTv.setText(res);
                            Gson gson = new Gson();
                            News news = gson.fromJson(res, News.class);
                            contentTv.setText("接收到数据："+news.getDay());
                        }else{
                            Toast.makeText(MainActivity.this, "请求失败："+response.code(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });


    }

    public void okhttpPost(View view) {
        FormBody body = new FormBody.Builder()
                .add("username", "zhangsan")
                .add("password", "123456")
                .build();

        Request request = new Request.Builder()
                .url(urlString)
                .post(body)
                .build();

        // 创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

            }
        });
    }
}